﻿Ext.define('app.ux.LinkColumn',
{
    extend: 'Ext.grid.column.Column',
    header: '&#160;',
    linkIdRe: /x-link-col-(\d+)/,
    constructor: function (cfg) {
        var me = this,
            items = cfg.items || (me.items = [me]),
            l = items.length,
            i,
            item;

        me.superclass.constructor.call(me, cfg);

        me.renderer = function (v, meta) {
            //          Allow a configured renderer to create initial value (And set the other values in the "metadata" argument!)
            v = Ext.isFunction(cfg.renderer) ? cfg.renderer.apply(this, arguments) || '' : '';

            meta.css += ' x-link-col-cell';
            for (i = 0; i < l; i++) {
                item = items[i];
                v += '<a href="javascript:;" class="x-link-col-icon x-link-col-' + String(i) + ' ' + (Ext.isFunction(item.getClass) ? item.getClass.apply(item.scope || this.scope || this, arguments) : '') + '"' +
                    ((item.tooltip) ? ' ext:qtip="' + item.tooltip + '"' : '') + '>' + (item.text || '') + '</a>';
                if (i < l - 1) v += '&nbsp;&nbsp;&nbsp;&nbsp;';
            }
            return v;
        };
    },

    destroy: function () {
        var me = this;
        delete me.items;
        delete me.renderer;
        return me.superclass.destroy.apply(this, arguments);
    },

    /**
     * @private
     * Process and refire events routed from the GridView's processEvent method.
     * Also fires any configured click handlers. By default, cancels the mousedown event to prevent selection.
     * Returns the event handler's status to allow cancelling of GridView's bubbling process.
     */
    processEvent: function (name, e, grid, rowIndex, colIndex) {
        var me = this;
        var m = e.getTarget().className.match(this.linkIdRe),
            item, fn;
        if (m && (item = this.items[parseInt(m[1], 10)])) {
            if (name == 'click') {
                (fn = item.handler || this.handler) && fn.call(item.scope || this.scope || this, grid, rowIndex, colIndex, item, e);
            } else if ((name == 'mousedown') && (item.stopSelection !== false)) {
                return false;
            }
        }
        return me.superclass.processEvent.apply(this, arguments);
    }
});
